import sys
import sexp
import nsynth
import fbsynth


def strip_comments(bm_file):
    no_comments = '('
    for line in bm_file:
        line = line.split(';', 1)[0]
        no_comments += line
    return no_comments + ')'


def print_answer(ans):
    if ans is None:
        return False
    print(ans)
    return True


def run_synthesis():
    b_file = open(sys.argv[1])
    bm = strip_comments(b_file)
    bm_expr = sexp.sexp.parseString(bm, parseAll=True).asList()[0]
    fbsynth.fallback_prepare(bm_expr)
    try:
        nsynth.enhanced_synth_prepare(bm_expr)
        while True:
            if print_answer(nsynth.normal_iteration()):
                return
            if print_answer(nsynth.reduce_task_iteration()):
                return
            if print_answer(fbsynth.fallback_iteration()):
                return
            if print_answer(fbsynth.reduce_task_iteration()):
                return
    except nsynth.NotSimpleSynthesisError:
        while True:
            if print_answer(fbsynth.fallback_iteration()):
                return
            if print_answer(fbsynth.reduce_task_iteration()):
                return


if __name__ == '__main__':
    run_synthesis()
